const axios = require("axios");

class AxiosClient {

    async getFirstAlbumTitle() {
        return await this.sendGetRequest('https://jsonplaceholder.typicode.com/albums',
            (response) => {
                let data = response.data;
                let title = data[0].title;
                return title;
            }
        );
    }

    async getSimpleResponseData(url) {
        return await this.sendGetRequest(url,
            (response) => {
                return response.data;
            }
        );
    }

    streamToString(stream) {
        const chunks = []
        return new Promise((resolve, reject) => {
            stream.on('data', chunk => chunks.push(chunk))
            stream.on('error', reject)
            stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
        })
    }

    async readFileData(url) {
        return await this.sendGetRequest(url,
            async (response) => {
                let contents = await this.streamToString(response.data);
                console.debug("Contents:", contents);
                return contents;
            }
        );
    }
    async sendGetRequest(url, callback) {
        const response = await axios.get(url);
        return callback(response);
    }
}

module.exports = AxiosClient;
